import React, { useState } from 'react';
import { Button, Input } from '../components/UI';
import { useChat } from '../hooks';
import { getWebSocketUrl } from '../utils';
import { generateUUID, generateUserColor } from '../utils/common';

interface LoginPageProps {
  onLogin: (username: string) => void;
}

export const LoginPage: React.FC<LoginPageProps> = ({ onLogin }) => {
  const [username, setUsername] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [error, setError] = useState('');
  const { connect, setUser } = useChat();
  
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!username.trim()) {
      setError('请输入用户名');
      return;
    }
    
    if (username.trim().length < 2) {
      setError('用户名至少需要2个字符');
      return;
    }
    
    if (username.trim().length > 20) {
      setError('用户名不能超过20个字符');
      return;
    }
    
    setIsLoading(true);
    setError('');
    
    try {
      // 连接WebSocket
      // 使用工具函数获取WebSocket地址
      const wsUrl = getWebSocketUrl();
      connect(wsUrl);
      // 立即设置全局用户，避免进入聊天页后短暂的 user 为空
      const userId = generateUUID();
      setUser({
        username: username.trim(),
        userId: userId,
        randomColor: generateUserColor(userId), // 使用基于用户ID的确定性颜色
      });
      
      // 调用登录回调
      onLogin(username.trim());
    } catch (err) {
      setError('连接失败，请重试');
      console.error('Login error:', err);
    } finally {
      setIsLoading(false);
    }
  };
  
  return (
    <div className="min-h-screen relative overflow-hidden">
      {/* 清晰静态渐变背景（无模糊/动画） */}
      <div className="absolute inset-0 bg-gradient-to-br from-emerald-50 via-cyan-50 to-blue-50" />

      <div className="relative min-h-screen flex items-center justify-center p-6">
      <div className="w-full max-w-md">
        <div className="bg-white border border-slate-200 rounded-2xl shadow-md p-8">
          <div className="text-center mb-6">
            <div className="w-12 h-12 mx-auto mb-3 rounded-xl bg-gradient-to-br from-indigo-500 to-blue-500 flex items-center justify-center shadow-md shadow-indigo-300/40">
              <svg className="w-6 h-6 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z" />
              </svg>
            </div>
            <h1 className="text-[22px] font-semibold tracking-tight text-slate-900">进入聊天室</h1>
          </div>

          {/* 简洁功能图标行（提示用 tooltip） */}
          <div className="flex items-center justify-center gap-4 mb-5 text-slate-500">
            <span title="拖拽上传">
              <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v8" />
              </svg>
            </span>
            <span title="粘贴图片">
              <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 7V5a2 2 0 012-2h4a2 2 0 012 2v2M5 7h14v12a2 2 0 01-2 2H7a2 2 0 01-2-2V7z" />
              </svg>
            </span>
            <span title="视频预览">
              <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 10l4.553-2.276A1 1 0 0121 8.618v6.764a1 1 0 01-1.447.894L15 14M4 6h10a2 2 0 012 2v8a2 2 0 01-2 2H4a2 2 0 01-2-2V8a2 2 0 012-2z" />
              </svg>
            </span>
            <span title="断点续传">
              <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v1m0 14v1m8-8h1M3 12H2m15.364 6.364l.707.707M5.636 6.343l-.707-.707m12.728 0l.707-.707M5.636 17.657l-.707.707M8 12a4 4 0 108 0 4 4 0 10-8 0z" />
              </svg>
            </span>
          </div>

          <form onSubmit={handleSubmit} className="space-y-5">
            <Input
              type="text"
              value={username}
              onChange={(e) => {
                setUsername(e.target.value);
                setError('');
              }}
              placeholder="用户名"
              error={error}
              disabled={isLoading}
              autoFocus
              maxLength={20}
            />

            <Button
              type="submit"
              variant="primary"
              size="lg"
              className="w-full"
              disabled={isLoading || !username.trim()}
              loading={isLoading}
            >
              {isLoading ? (
                '连接中...'
              ) : (
                <div className="flex items-center justify-center gap-2">
                  {/* 发送/进入：纸飞机图标 */}
                  <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3.055 11.168l16.664-7.2a.75.75 0 011.02.96l-6.06 15.14a.75.75 0 01-1.398-.06l-1.42-4.26a.75.75 0 00-.47-.47l-4.26-1.42a.75.75 0 01-.076-1.39z" />
                  </svg>
                  <span>进入</span>
                </div>
              )}
            </Button>
          </form>
        </div>
      </div>
      </div>
    </div>
  );
}